#include <iconv.h>
#include <string.h>

int is_ascii(unsigned char ch)
{
	if (ch > 0 && ch < 128)
		return 1;
	else
		return 0;
}

/*
 * 返回0为gb2312的汉字,返回1为gb2312的标点
 * 返回2是ascii,其他编码返回3
 **/
/*
int encoding(unsigned char *chs)
{
	if (*chs >= 0xb0 && *chs <= 0xf7 && *(chs + 1) >= 0xa1 && *(chs + 1) <= 0xfe)
		return 0;
	else if (*chs >= 0xA1 && *chs <= 0xAF && *(chs + 1) >= 0xA1 && *(chs + 1) <= 0xFF)
		return 1;
	else if (is_ascii(*chs))
		return 2;
	else return 3;
}
*/

static int code_convert(char *from_charset,char *to_charset,char *inbuf,int inlen,char *outbuf,int outlen)
{
	iconv_t cd;
	char **pin = &inbuf;
	char **pout = &outbuf;
	
	cd = iconv_open(to_charset,from_charset);
	if (cd==0) return -1;
	memset(outbuf,0,outlen);
	if (iconv(cd,pin,(size_t *)&inlen,pout,(size_t *)&outlen)==-1) return -1;
	iconv_close(cd);
	return 0;
}
int u2g(char *inbuf,int inlen,char *outbuf,int outlen)
{
	return code_convert("utf-8","gb2312",inbuf,inlen,outbuf,outlen);
}
int g2u(char *inbuf,size_t inlen,char *outbuf,size_t outlen)
{
	return code_convert("gb2312","utf-8",inbuf,inlen,outbuf,outlen);
}
